package com.da.lon.wang.xlg.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.bean.ChangeBean;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.http.HttpLoader.OnWebLoadListener;
import com.da.lon.wang.xlg.util.PreferenceUtils;
import com.da.lon.wang.xlg.util.ToastUtils;
import com.da.lon.wang.xlg.util.Utils;
import com.da.lon.wang.xlg.util.XLGDataUtils;
import com.da.lon.wang.xlg.view.AddressPopupWindow;
import com.umeng.analytics.MobclickAgent;

import net.tsz.afinal.http.AjaxParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class EditAddressActivity extends BaseActivity implements
        OnClickListener, AMapLocationListener {

    String[] mProvinceDatas;
    String[] mProvinceDatasId;
    Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    Map<String, String[]> mCitisDatasIdMap = new HashMap<String, String[]>();
    Map<String, String[]> mAreaDatasMap = new HashMap<String, String[]>();
    Map<String, String[]> mAreaDatasIdMap = new HashMap<String, String[]>();
    private Context context;
    private EditText pnameText, pphoneText, pidText, paddressText;
    private TextView plocationView;
    private ImageButton backButton;
    private TextView rightView, titleView, deletView;
    private LinearLayout sureLayout;
    private Button sureButton;
    private AddressPopupWindow addressWindow;
    private String adname;
    private String adphone;
    private String adlocation;
    private String adaddress;
    private String addid;
    private String user_id;
    private String proviceid = "";
    private String cityid = "";
    private String areaid = "";
    private String bodycard;
    private HttpLoader<ChangeBean> loader;
    private int resultCode = 1;
    private AMapLocationClient locationClient;
    private AMapLocationClientOption locationOption;
    private int key;
    private String pro_type = null;
    private String defult_address;
    private ImageView ouka_address_right_iv;
    Handler mHandler = new Handler() {
        public void dispatchMessage(android.os.Message msg) {
            switch (msg.what) {
                // 开始定位
                case Utils.MSG_LOCATION_START:
                    plocationView.setText("正在定位...");
                    plocationView.setEnabled(false);
                    ouka_address_right_iv.setEnabled(false);
                    break;
                // 定位完成
                case Utils.MSG_LOCATION_FINISH:
                    plocationView.setEnabled(true);
                    ouka_address_right_iv.setEnabled(true);
                    StringBuffer sb = new StringBuffer();
                    AMapLocation loc = (AMapLocation) msg.obj;
                    if (null != loc && loc.getErrorCode() == 0) {
                        initDatas(context);
                        adlocation = loc.getProvince() + "," + loc.getCity() + ","
                                + loc.getDistrict();
                        if (!loc.getProvince().equals("")
                                && !loc.getCity().equals("")) {
                            plocationView.setText(adlocation);
                        } else {
                            plocationView.setText("省,市,区");
                        }
                        adaddress = loc.getAddress().replaceAll(loc.getCity(), "")
                                .replaceAll(loc.getDistrict(), "")
                                .replaceAll(loc.getProvince(), "");
                        paddressText.setText(adaddress);
                    } else {
                        plocationView.setText("省,市,区");
                        ToastUtils.showShort(EditAddressActivity.this, "定位失败！");

                    }
                    break;
                // 停止定位
                case Utils.MSG_LOCATION_STOP:
                    break;
                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = getIntent();
        adname = intent.getStringExtra("adname");
        adphone = intent.getStringExtra("adphone");
        adlocation = intent.getStringExtra("adlocation");
        adaddress = intent.getStringExtra("adaddress");
        addid = intent.getStringExtra("addid");
        bodycard = intent.getStringExtra("bodycard");
        proviceid = intent.getStringExtra("proviceid");
        cityid = intent.getStringExtra("cityid");
        areaid = intent.getStringExtra("areaid");
        key = intent.getIntExtra("key", 2);
        pro_type = intent.getStringExtra("pro_type");
        defult_address = intent.getStringExtra("defult_address");

        PreferenceUtils.getInstance().SetSettingString(
                PreferencesConfig.AREA_ID, areaid);
        initView();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ouka_address_edit);
        context = this;
        PreferenceUtils.getInstance().SetSettingString(
                PreferencesConfig.PROVICE_ID, null);
        PreferenceUtils.getInstance().SetSettingString(
                PreferencesConfig.CITY_ID, null);
        PreferenceUtils.getInstance().SetSettingString(
                PreferencesConfig.AREA_ID, null);
    }

    private void initView() {
        pnameText = (EditText) findViewById(R.id.person_name);
        pphoneText = (EditText) findViewById(R.id.person_phone);
        pidText = (EditText) findViewById(R.id.person_id);
        paddressText = (EditText) findViewById(R.id.person_address);
        ouka_address_right_iv = (ImageView) findViewById(R.id.ouka_address_right_iv);
        if (null != pro_type && !"0".equals(pro_type)) {
            pidText.setHint("身份证信息必填");
        }

        plocationView = (TextView) findViewById(R.id.person_location);
        plocationView.setOnClickListener(this);

        backButton = (ImageButton) findViewById(R.id.ouka_address_left);
        titleView = (TextView) findViewById(R.id.title);
        rightView = (TextView) findViewById(R.id.ouka_address_right);

        deletView = (TextView) findViewById(R.id.ouka_address_delet);
        sureButton = (Button) findViewById(R.id.ouka_address_sure);
        sureLayout = (LinearLayout) findViewById(R.id.address_sure);

        backButton.setOnClickListener(this);
        rightView.setOnClickListener(this);
        ouka_address_right_iv.setOnClickListener(this);
        sureButton.setOnClickListener(this);
        deletView.setOnClickListener(this);

        if (addid != null) {
            if (adname != null) {
                pnameText.setText(adname);
            }
            if (adphone != null) {
                pphoneText.setText(adphone);
            }
            if (adlocation != null) {
                plocationView.setText(adlocation);
            }
            if (adaddress != null) {
                paddressText.setText(adaddress);
            }
            if (bodycard != null) {
                pidText.setText(bodycard);
            }
            deletView.setVisibility(View.VISIBLE);
            titleView.setText("修改");
        } else if (null != defult_address && !"".equals(defult_address)
                && defult_address.equals("1")) {
            sureButton.setText("保存默认地址");
        } else {
            sureButton.setText("保存");
        }

        if (key == 0) {
            Utils.startLocationClientAddress(context, mHandler);
        } else {
            rightView.setVisibility(View.VISIBLE);
            ouka_address_right_iv.setVisibility(View.GONE);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.person_location:
                // 实例化SelectPicPopupWindow
                MyApplication.getInstance().hideInputWindow(pnameText, context);
                MyApplication.getInstance().hideInputWindow(pphoneText, context);
                MyApplication.getInstance().hideInputWindow(pidText, context);
                MyApplication.getInstance().hideInputWindow(paddressText, context);
                addressWindow = new AddressPopupWindow(context, plocationView,
                        plocationView.getText().toString(), key);
                // 显示窗口
                addressWindow.showAtLocation(plocationView, Gravity.BOTTOM
                        | Gravity.CENTER_HORIZONTAL, 0, 0);

                break;

            case R.id.ouka_address_left:
                finish();
                break;

            case R.id.ouka_address_right:
                saveAddress();
                break;

            // 重新定位
            case R.id.ouka_address_right_iv:
                Utils.startLocationClientAddress(context, mHandler);
                break;

            case R.id.ouka_address_sure:
                if (key == 0) {
                    saveAddress();
                } else {
                    setDefultAddress();
                }
                break;

            case R.id.ouka_address_delet:

                loader = new HttpLoader<ChangeBean>(this, XLGConstants.URL
                        + "Shipping-addressdel", ChangeBean.class, 60 * 1000);
                AjaxParams params1 = new AjaxParams();
                params1.put("token", XLGDataUtils.encrypt2MD5("Shipping"
                        + "2015#$%" + "addressdel"));
                params1.put("addid", addid);

                loader.setManagerListener(new OnWebLoadListener<ChangeBean>() {

                    @Override
                    public void OnStart() {
                        showDialog();
                    }

                    @Override
                    public void OnError(String error) {
                        dismissDialog();
                    }

                    @Override
                    public void onSuccess(ChangeBean t) {
                        dismissDialog();
                        if (t != null && "000000".equals(t.getCode())) {
                            finish();
                        }
                    }
                });
                loader.loadData(params1);

                break;

            default:
                break;
        }
    }

    @Override
    public void onLocationChanged(AMapLocation loc) {
        if (null != loc) {
            Message msg = mHandler.obtainMessage();
            msg.obj = loc;
            msg.what = Utils.MSG_LOCATION_FINISH;
            mHandler.sendMessage(msg);
        }
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (null != locationClient) {
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }


    private void initDatas(Context context) {

        try {
            JSONArray jsonArray = Utils.initJsonData(context).getJSONArray(
                    "locationlist");
            mProvinceDatas = new String[jsonArray.length()];
            mProvinceDatasId = new String[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonP = jsonArray.getJSONObject(i);// 每个省的json对象
                String province = jsonP.getString("name");// 省名字

                String provinceId = jsonP.getString("id");

                mProvinceDatas[i] = province;

                mProvinceDatasId[i] = provinceId;

                JSONArray jsonCs = null;

                jsonCs = jsonP.getJSONArray("city");

                String[] mCitiesDatas = new String[jsonCs.length()];
                String[] mCitiesDatasId = new String[jsonCs.length()];
                for (int j = 0; null != jsonCs && j < jsonCs.length(); j++) {
                    JSONObject jsonCity = jsonCs.getJSONObject(j);
                    String city = jsonCity.getString("name");// 市名字

                    String cityId = jsonCity.getString("id");

                    mCitiesDatas[j] = city;

                    mCitiesDatasId[j] = cityId;
                    JSONArray jsonAreas = null;
                    try {
                        /**
                         * Throws JSONException if the mapping doesn't exist or
                         * is not a JSONArray.
                         */
                        jsonAreas = jsonCity.getJSONArray("county");
                    } catch (Exception e) {
                        continue;
                    }

                    String[] mAreasDatas = new String[jsonAreas.length()];// 当前市的所有区
                    String[] mAreasDatasId = new String[jsonAreas.length()];
                    for (int k = 0; null != jsonAreas && k < jsonAreas.length(); k++) {
                        String area = jsonAreas.getJSONObject(k).getString(
                                "name");// 区域的名称

                        String areaId = jsonAreas.getJSONObject(k).getString(
                                "id");

                        mAreasDatas[k] = area;
                        mAreasDatasId[k] = areaId;
                    }
                    mAreaDatasMap.put(city, mAreasDatas);
                    mAreaDatasIdMap.put(cityId, mAreasDatasId);
                }

                mCitisDatasMap.put(province, mCitiesDatas);
                mCitisDatasIdMap.put(provinceId, mCitiesDatasId);
            }

        } catch (JSONException e) {

        }
    }


    private String getProvinceIdByProvinceName(String provinceName) {
        String cuProviceid = "";
        try {
            for (int i = 0; null != mProvinceDatas && i < mProvinceDatas.length; i++) {
                if (provinceName.contains(mProvinceDatas[i])) {
                    cuProviceid = mProvinceDatasId[i];
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return cuProviceid;
    }


    private String getCityIdByProvinceName(String provinceName, String cityName) {
        String cuCityID = "";
        try {
            String[] cityNameL = mCitisDatasMap.get(provinceName.substring(0,
                    provinceName.length() - 1));
            String[] cityIDL = mCitisDatasIdMap
                    .get(getProvinceIdByProvinceName(provinceName));
            for (int i = 0; null != cityNameL && i < cityNameL.length; i++) {
                if (cityName.contains(cityNameL[i])) {
                    cuCityID = cityIDL[i];
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return cuCityID;
    }


    private String getAreaIdByProvinceName(String provinceName,
                                           String cityName, String areaName) {
        String cuAreaID = "";
        if (areaName == null || areaName.trim().equals("")) {
            return null;
        }
        try {
            String[] areaNameL = mAreaDatasMap.get(cityName.substring(0,
                    cityName.length() - 1));
            String[] areaIDL = mAreaDatasIdMap.get(getCityIdByProvinceName(
                    provinceName, cityName));
            for (int i = 0; null != areaNameL && i < areaNameL.length; i++) {
                if (areaName.contains(areaNameL[i])) {
                    cuAreaID = areaIDL[i];
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return cuAreaID;
    }


    private boolean isPro_Type(String pro_type) {
        if (null == pro_type || "0".equals(pro_type)) {
            return false;
        } else if (null != pro_type
                && !"0".equals(pro_type)
                && XLGDataUtils.isIdentityCard(pidText.getText().toString()
                .trim())) {
            return false;
        } else {
            return true;
        }

    }


    private boolean isVerification() {
        if ("".equals(paddressText.getText().toString())
                || pphoneText.getText().toString().trim().length() != 11
                || "".equals(pnameText.getText().toString())
                || isPro_Type(pro_type)) {
            Toast.makeText(EditAddressActivity.this, "信息未填写完整,或者格式不正确",
                    Toast.LENGTH_SHORT).show();
            return false;
        } else {
            return true;
        }

    }


    private void saveAddress() {
        try {
            if (addid != null && adlocation != null) {

                if (isVerification()) {
                    String p_id = PreferenceUtils.getInstance().getSettingStr(
                            PreferencesConfig.PROVICE_ID, "");
                    String c_id = PreferenceUtils.getInstance().getSettingStr(
                            PreferencesConfig.CITY_ID, "");
                    String a_id = PreferenceUtils.getInstance().getSettingStr(
                            PreferencesConfig.AREA_ID, "");
                    if (p_id != null && !"".equals(p_id)) {
                        proviceid = p_id;
                    }
                    if (c_id != null && !"".equals(c_id)) {
                        cityid = c_id;
                    }
                    if (a_id != null && !"".equals(a_id)) {
                        areaid = a_id;
                    } else {
                        areaid = "";
                    }
                    loader = new HttpLoader<ChangeBean>(this, XLGConstants.URL
                            + "/Shipping-addressedit", ChangeBean.class,
                            60 * 1000);
                    AjaxParams params = new AjaxParams();
                    params.put("token", XLGDataUtils.encrypt2MD5("Shipping"
                            + "2015#$%" + "addressedit"));
                    params.put("id", MyApplication.getUserId());
                    params.put("addid", addid);
                    params.put("provinceid", proviceid);
                    params.put("city", cityid);
                    if (!areaid.equals("")) {
                        params.put("county", areaid);
                    }
                    params.put("address", paddressText.getText().toString());
                    params.put("telphone", pphoneText.getText().toString());
                    params.put("real_name", pnameText.getText().toString());
                    params.put("body_card_number", pidText.getText().toString());

                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.CARD_NUMBER,
                            pidText.getText().toString());

                    loader.setManagerListener(new OnWebLoadListener<ChangeBean>() {

                        @Override
                        public void OnStart() {
                            showDialog();
                        }

                        @Override
                        public void OnError(String error) {
                            dismissDialog();
                        }

                        @Override
                        public void onSuccess(ChangeBean t) {
                            dismissDialog();
                            if (t != null && "000000".equals(t.getCode())) {
                                finish();
                            }

                        }
                    });
                    loader.loadData(params);
                }
            } else {
                String pname = "", cname = "", areaname = "";
                if (adlocation != null && !adlocation.contains("省,市,区")
                        && adlocation.trim().length() > 0
                        && adlocation.split(",").length > 0) {
                    pname = adlocation.split(",")[0];
                    cname = adlocation.split(",")[1];
                    if (adlocation.split(",").length > 1) {
                        areaname = adlocation.split(",")[2];
                    }
                }

                proviceid = PreferenceUtils.getInstance().getSettingStr(
                        PreferencesConfig.PROVICE_ID,
                        getProvinceIdByProvinceName(pname));
                cityid = PreferenceUtils.getInstance().getSettingStr(
                        PreferencesConfig.CITY_ID,
                        getCityIdByProvinceName(pname, cname));
                areaid = PreferenceUtils.getInstance().getSettingStr(
                        PreferencesConfig.AREA_ID,
                        getAreaIdByProvinceName(pname, cname, areaname));

                if ("".equals(proviceid) || "".equals(cityid)) {
                    Toast.makeText(this, "还没有选择城市", Toast.LENGTH_SHORT).show();
                } else {
                    if (isVerification()) {
                        loader = new HttpLoader<ChangeBean>(this,
                                XLGConstants.URL + "/Shipping-addressadd",
                                ChangeBean.class, 60 * 1000);
                        AjaxParams params = new AjaxParams();
                        params.put("token", XLGDataUtils.encrypt2MD5("Shipping"
                                + "2015#$%" + "addressadd"));
                        params.put("id", MyApplication.getUserId());
                        params.put("provinceid", proviceid);
                        params.put("city", cityid);
                        params.put("county", areaid);
                        params.put("user_key", MyApplication.getUserKey());
                        params.put("address", paddressText.getText().toString());
                        params.put("telphone", pphoneText.getText().toString());
                        params.put("real_name", pnameText.getText().toString());
                        params.put("defult_address", defult_address);
                        params.put("body_card_number", pidText.getText()
                                .toString());

                        PreferenceUtils.getInstance().SetSettingString(
                                PreferencesConfig.CARD_NUMBER,
                                pidText.getText().toString());

                        loader.setManagerListener(new OnWebLoadListener<ChangeBean>() {

                            @Override
                            public void OnStart() {
                                showDialog();
                            }

                            @Override
                            public void OnError(String error) {
                                dismissDialog();
                            }

                            @Override
                            public void onSuccess(ChangeBean t) {
                                dismissDialog();
                                if (t != null && "000000".equals(t.getCode())) {
                                    Intent intent1 = new Intent();
                                    intent1.putExtra("addid", t.getResult()
                                            .getAdd_id());
                                    intent1.putExtra("bodynumber", t
                                            .getResult().getBody_card_number());
                                    setResult(resultCode, intent1);
                                    finish();
                                }

                            }
                        });
                        loader.loadData(params);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void setDefultAddress() {
        user_id = PreferenceUtils.getInstance().getSettingStr(
                PreferencesConfig.USER_ID, "");

        loader = new HttpLoader<ChangeBean>(this, XLGConstants.URL
                + "Shipping-addressdef", ChangeBean.class, 60 * 1000);
        AjaxParams params = new AjaxParams();
        params.put("token", XLGDataUtils.encrypt2MD5("Shipping" + "2015#$%"
                + "addressdef"));
        params.put("id", user_id);
        params.put("addid", addid);

        loader.setManagerListener(new OnWebLoadListener<ChangeBean>() {

            @Override
            public void OnStart() {
                showDialog();
            }

            @Override
            public void OnError(String error) {
                dismissDialog();
            }

            @Override
            public void onSuccess(ChangeBean t) {
                dismissDialog();
                if (t != null && "000000".equals(t.getCode())) {
                    finish();
                }

            }
        });
        loader.loadData(params);


    }

}
